//
//  UzysAsset.m
//  XPSite
//
//  Created by zhuxietong on 2017/2/3.
//  Copyright © 2017年 zhuxietong. All rights reserved.
//

#import "UzysAsset.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <UIKit/UIKit.h>
//#import "SmoSky-Swift.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

@interface NSFileManager (Fast)

+(void)removeFileWith:(NSString*)prefix;

@end


@implementation NSFileManager (fast)

+(void)removeFileWith:(NSString*)prefix{
    
    NSString * temp = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray * fileArray = [fileManager subpathsAtPath:temp];
    if (fileManager != nil)
    {
        for (NSString * fn in fileArray) {
            if ([fn hasPrefix:prefix])
            {
                @try{
                    NSError *error;
                    NSString *path = [NSString stringWithFormat:@"%@/%@",temp,fn];
                    [fileManager removeItemAtPath:path error:&error];
                }@catch(NSException * e){
                    
                }
            }
        }
    }
}

@end
//
//@objc public static func removeTmp(filePrefix:String)
//{
//
//    //        var path:Array = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask,true)
//    //        let d_path = (path[0] as String) + "/tmp"
//
//    let temp = NSTemporaryDirectory()
//    let fileManager = FileManager.default
//    guard let fileArray = fileManager.subpaths(atPath: temp) else {return}
//
//    for fn in fileArray{
//
//        //            print("KKKOOO|\(fn)")
//        if fn.hasPrefix(filePrefix)
//        {
//            //                print("==========KK|\(filePrefix)")
//            try! fileManager.removeItem(atPath: temp + "/\(fn)")
//        }
//    }
//
//}

@implementation UzysAsset

+ (NSMutableArray*)parserImages:(NSArray*)assets{
    
    NSMutableArray *imgs = [[NSMutableArray alloc] init];
    
    if([[assets[0] valueForProperty:@"ALAssetPropertyType"] isEqualToString:@"ALAssetTypePhoto"]) //Photo
    {
        
        [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ALAsset *representation = obj;
            
            UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
                                               scale:representation.defaultRepresentation.scale
                                         orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
            [imgs addObject:img];
            //            *stop = YES;
        }];
    }
    
    return imgs;
    
    
}

+ (NSMutableArray*)parserVideos:(NSArray *)assets complate:(void (^)(void))block;
{
    
    NSMutableArray *videos = [[NSMutableArray alloc] init];
    [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {


    ALAsset *alAsset = assets[0];
    
    UIImage *img = [UIImage imageWithCGImage:alAsset.defaultRepresentation.fullResolutionImage
                                       scale:alAsset.defaultRepresentation.scale
                                 orientation:(UIImageOrientation)alAsset.defaultRepresentation.orientation];
    NSMutableDictionary * info = [[NSMutableDictionary alloc] init];

    if (img != nil)
    {
        [info setObject:img forKey:@"img"];
    }

        [NSFileManager removeFileWith:[NSString stringWithFormat:@"%@",@"_video"]];
    
    ALAssetRepresentation *representation = alAsset.defaultRepresentation;
    NSURL *movieURL = representation.url;
    [info setObject:movieURL forKey:@"_url"];

    NSString * videoName = [NSString stringWithFormat:@"_video%d",0];


    [info setObject:[NSString stringWithFormat:@"%lld",[[alAsset defaultRepresentation] size]] forKey:@"file_size"];
//    NSLog(@"-----ddd---%@",movieURL);
    
    NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:videoName] stringByAppendingString:@".mp4"]];
    AVAsset *asset      = [AVURLAsset URLAssetWithURL:movieURL options:nil];
    CMTime ctime = [asset duration];
    Float64 ftime = CMTimeGetSeconds(ctime);
    [info setObject:[NSString stringWithFormat:@"%f",ftime] forKey:@"duration"];
    
    AVAssetExportSession *session =
    [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    
    session.outputFileType  = AVFileTypeQuickTimeMovie;
    session.outputURL       = uploadURL;
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        
        if (session.status == AVAssetExportSessionStatusCompleted)
        {
            [info setObject:uploadURL forKey:@"url"];
            NSString * path = [uploadURL.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""];
            [info setObject:path forKey:@"path"];
//            NSLog(@"kdddkdkdk===|%@",info);

        }
        block();
        
    }];
    [videos addObject:info];
    }];

    return videos;
    
}


@end
